package com.hbnu.service.impl;

import com.hbnu.dao.DormManagerDao;
import com.hbnu.dao.UserDao;
import com.hbnu.dao.impl.DormManagerDaoImpl;
import com.hbnu.dao.impl.UserDaoImpl;
import com.hbnu.pojo.DormBuild;
import com.hbnu.pojo.PageModel;
import com.hbnu.pojo.User;
import com.hbnu.service.UserService;

import java.util.List;

/**
 * @author chendikai
 * @date 2024-11-06 上午 10:37
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    private DormManagerDao dormManagerDao = new DormManagerDaoImpl();

    @Override
    public User findUserByStuCodeAndPassword(String stuCode, String password) {

        return userDao.findUserByStuCodeAndPassword(stuCode, password);
    }

    @Override
    public List<User> findAllManager(String searchType, String keyword) {

        List<User> userList = userDao.findManager(searchType, keyword);

        // 根据管理员id查询所管理的宿舍楼信息
        if (null != userList) {
            for (User user : userList) {
                List<DormBuild> dormBuilds = dormManagerDao.findByUserId(user.getId());
                user.setDormBuilds(dormBuilds);
            }
        }

        return userList;
    }

    @Override
    public void saveManager(User user, String[] dormBuildIds) {

        // 找到数据库中宿舍管理员中最大的学号+1作为当前要保存的宿舍管理员的学号
        String managerStuCodeMax = userDao.findManagerStuCodeMax();
        user.setStuCode(managerStuCodeMax);
        // 保存宿舍管理员
        Integer userId = userDao.saveManager(user);
        // 保存宿舍管理员和宿舍楼的中间表
        dormManagerDao.saveManagerAndBuild(userId, dormBuildIds);

    }

    @Override
    public User findById(int id) {
        return userDao.findById(id);
    }

    @Override
    public void updateManager(User user) {
        userDao.updateManager(user);
    }

    @Override
    public List<User> findStudent(String dormBuildId, String searchType, String keyword, User user, PageModel pageModel) {
        StringBuffer sql = new StringBuffer();
        // 不管当前用户角色是怎么样，查询的都是学生，所有role_id=2
        sql.append("SELECT user.*,build.name buildName,build.* FROM tb_user user " + " LEFT JOIN tb_dormBuild build ON build.id = user.dormBuildId " + " where user.role_id = 2");

        if (keyword != null && !keyword.equals("") && "name".equals(searchType)) {
            //根据名字查找
            sql.append(" and user.name like '%" + keyword.trim() + "%'");
        } else if (keyword != null && !keyword.equals("") && "stuCode".equals(searchType)) {
            //根据学号查找
            sql.append(" and user.stu_code = '" + keyword.trim() + "'");
        } else if (keyword != null && !keyword.equals("") && "dormCode".equals(searchType)) {
            //根据宿舍编号查找
            sql.append(" and user.dorm_code = '" + keyword.trim() + "'");
        } else if (keyword != null && !keyword.equals("") && "sex".equals(searchType)) {
            //根据性别查找
            sql.append(" and user.sex = '" + keyword.trim() + "'");
        } else if (keyword != null && !keyword.equals("") && "tel".equals(searchType)) {
            //根据电话号码查找
            sql.append(" and user.tel = '" + keyword.trim() + "'");
        }
        if (dormBuildId != null && !dormBuildId.equals("")) {
            //根据宿舍楼ID查找
            sql.append(" and user.dormBuildId = '" + dormBuildId + "'");
        }

        /*sql.append(" and user.dormBuildId in (2,3,4)")*/
        // 判断当前用户是否为宿舍管理员，如是则需查询其管理的所有宿舍楼id
        if(user.getRoleId().equals(1)){
            // 获取当前宿舍管理员管理的所有宿舍楼
            List<DormBuild> builds = dormManagerDao.findByUserId(user.getId());

            sql.append(" and user.dormBuildId in (");
            for (int i = 0; i < builds.size(); i++) {
                sql.append(builds.get(i).getId() + ",");
            }
// 删除最后一个,
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
        }
        sql.append(" limit " + pageModel.getStartNum() + " , " +
                pageModel.getPageSize());
        List<User> students = userDao.findStudent(sql.toString());
        return students;

    }

    @Override
    public Integer findTotalNum(String dormBuildId, String searchType, String keyword, User user) {
        StringBuffer sql = new StringBuffer();
        // 不管当前用户角色是怎么样，查询的都是学生，所有role_id=2
        sql.append("SELECT count(*) FROM tb_user user " + " LEFT JOIN tb_dormBuild build ON build.`id` = user.dormBuildId " + " where user.role_id = 2");

        if (keyword != null && !keyword.equals("") && "name".equals(searchType)) {
            //根据名字查找
            sql.append(" and user.name like '%" + keyword.trim() + "%'");
        } else if (keyword != null && !keyword.equals("") && "stuCode".equals(searchType)) {
            //根据学号查找
            sql.append(" and user.stu_code = '" + keyword.trim() + "'");
        } else if (keyword != null && !keyword.equals("") && "dormCode".equals(searchType)) {
            //根据宿舍编号查找
            sql.append(" and user.dorm_code = '" + keyword.trim() + "'");
        } else if (keyword != null && !keyword.equals("") && "sex".equals(searchType)) {
            //根据性别查找
            sql.append(" and user.sex = '" + keyword.trim() + "'");
        } else if (keyword != null && !keyword.equals("") && "tel".equals(searchType)) {
            //根据电话号码查找
            sql.append(" and user.tel = '" + keyword.trim() + "'");
        }
        if (dormBuildId != null && !dormBuildId.equals("")) {
            //根据宿舍楼ID查找
            sql.append(" and user.dormBuildId = '" + dormBuildId + "'");
        }

        /*sql.append(" and user.dormBuildId in (2,3,4)")*/
        // 判断当前用户是否为宿舍管理员，如是则需查询其管理的所有宿舍楼id
        if (user.getRoleId().equals(1)) {
            // 获取当前宿舍管理员管理的所有宿舍楼
            List<DormBuild> builds = dormManagerDao.findByUserId(user.getId());

            sql.append(" and user.dormBuildId in (");
            for (int i = 0; i < builds.size(); i++) {
                sql.append(builds.get(i).getId() + ",");
            }
// 删除最后一个,
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
        }
        return userDao.findTotalNum(sql.toString());
    }

    @Override
    public void updateStudent(User user1) {
        userDao.updateStudent(user1);

    }

    @Override
    public void saveStudent(User user2) {
        userDao.saveStudent(user2);
    }

    @Override
    public User findByStuCode(String stuCode) {
        return userDao.findByStuCode(stuCode);
    }

    @Override
    public User findByUserIdAndManager(Integer id, User user) {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from tb_user user where user.id =" + id);
        if (user.getRoleId() != null && user.getRoleId().equals(1)) {
// 表示当前登录的用户角色是宿舍管理员，则要求要修改的学生必须居住在该宿舍管理员管理的宿舍楼中
            List<DormBuild> builds = dormManagerDao.findByUserId(user.getId());
            sql.append(" and user.dormBuildId in (");
            for (int i = 0; i < builds.size(); i++) {
                sql.append(builds.get(i).getId() + ",");// (1,2,)
            }
            // 删除最后一个,
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
        }
        return userDao.findByUserIdAndManager(sql.toString());

    }

    @Override
    public User findStuCodeAndManager(String stuCode, User userCurr) {
        StringBuffer sql=new StringBuffer("select * from tb_user user where user.role_id=2 and user.stu_code='"+stuCode+"'");

        Integer roleId=userCurr.getRoleId();
        if(roleId!=null&&roleId.equals(1)){
            List<DormBuild> dormBuilds=dormManagerDao.findByUserId(userCurr.getId());

            sql.append(" and user.dormBuildId in (");
            for (int i = 0; i < dormBuilds.size(); i++) {
                 sql.append(dormBuilds.get(i).getId()+",");
            }

            sql.deleteCharAt(sql.length()-1);
            sql.append(")");

            return userDao.findStuCodeAndManager(sql.toString());
        }
        if(roleId!=null&&"2".equals(roleId)){
            return null;
        }

        return userDao.findStuCodeAndManager(sql.toString());
    }

    @Override
    public void updatePassword(User user) {
        userDao.updatePassword(user);
    }
}
